package com.smart4j.framework.helper;

import com.smart4j.framework.annotation.Inject;
import com.smart4j.framework.util.ReflectionUtil;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 依赖注入助手类
 *
 * @author 段誉
 * @create 2019-04-01 16:17
 */
public final class IocHelper {
  static {
    //获取所有的Bean类与Bean实例之间的映射关系（简称Bean Map）
    Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();

    if (MapUtils.isNotEmpty(beanMap)) {
      //遍历Bean Map
      for (Map.Entry<Class<?>, Object> beanEntry: beanMap.entrySet()) {
        //从BeanMap中获取Bean类与Bean实例
        Class<?> beanClass = beanEntry.getKey();
        Class<?> beanInstance = beanEntry.getKey();
        //获取bean类定义的所有成员变量（检测Bean Field）
        Field[] beanFields = beanClass.getDeclaredFields();

        //成员变量为空则直接跳出本次循环，进行下一次循环
        if (ArrayUtils.isEmpty(beanFields)) {
          continue;
        }

        for (Field beanField: beanFields) {
          //判断当前beanField是否带有Inject注解，不存在则跳出本次循环
          if (!beanField.isAnnotationPresent(Inject.class)) {
            continue;
          }

          //在Bean Map中获取BeanField对应的实例
          Class<?> beanFieldClass = beanField.getType();
          Object beanFieldInstance = beanMap.get(beanFieldClass);
          if (beanFieldInstance != null) {
            //通过反射初始化BeanField的值
            ReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);
          }

        }

      }
    }
  }
}
